#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
  int flags, opt, fd;
  mode_t perms;
  size_t size;
  void *addr;

  flags = O_RDWR;
  while ((opt = getopt(argc, argv, "cx")) != -1) {
    switch (opt) {
    case 'c': flags |= O_CREAT; break;
    case 'x': flags |= O_EXCL;  break;  
    default: 
      printf("Wrong options\n");
    }
  }
  size = atoi(argv[optind+1]);
  perms = S_IRUSR | S_IWUSR;
  fd = shm_open(argv[optind], flags, perms);
  if (fd == -1)
    printf("Failed to open shared memory\n");
  if (ftruncate(fd, size) == -1)
    printf("Failed to truncate size to %d\n", size);
  addr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
  if (addr == MAP_FAILED)
    printf("Failed to mmap\n");
  return 0;
}
